package com.nova.bluetooth.ui.device;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.lifecycle.ViewModelProvider;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.nova.bluetooth.AppMainActivity;
import com.nova.bluetooth.GuideActivity;
import com.nova.bluetooth.R;
import com.nova.bluetooth.base.BaseFragment;
import com.nova.bluetooth.databinding.FragmentFindDeviceBinding;
import com.nova.bluetooth.helpUtils.MapUtils;
import com.nova.bluetooth.helpUtils.OnClickEvent;
import com.nova.bluetooth.helpUtils.ToastUtils;
import com.nova.bluetooth.widget.CommonDialog;

/**
 * 查找设备
 */
public class FindDeviceFragment extends BaseFragment {
    private FragmentFindDeviceBinding binding;
    private FindDeviceViewModel mViewModel;
    private MapView mMapView;
    double mLatitude, mLongitude;
    double mLastLatitude, mLastLongitude = -1;
    private AMap mAMap;
    private UiSettings mUiSettings;
    private Bundle mSavedInstanceState;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_find_device, container, false);
        binding = FragmentFindDeviceBinding.bind(view);
        mViewModel = new ViewModelProvider(this).get(FindDeviceViewModel.class);
        initView();
        initData();
        return binding.getRoot();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSavedInstanceState = savedInstanceState;
    }

    private void initView() {
        binding.ivBack.setOnClickListener(onClickEvent);
        binding.ivGetLocation.setOnClickListener(onClickEvent);
        binding.ivPlayPause.setOnClickListener(onClickEvent);
        binding.ivGuide.setOnClickListener(onClickEvent);


        mMapView = binding.mapView;
        mMapView.onCreate(mSavedInstanceState);
        //初始化地图控制器对象
        mAMap = mMapView.getMap();
        mUiSettings = mAMap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(false);
    }

    private void initData() {
//        mViewModel.getGeodeLocation();
        mViewModel.mGeoLocationData.observe(getViewLifecycleOwner(), data -> {
            if (data != null) {
                mLatitude = data.getLatitude();
                mLongitude = data.getLongitude();

                // 计算距离
                if (mLastLatitude > 0 && mLastLongitude > 0) {
                    double distance = MapUtils.calculateDistance(mLatitude, mLongitude,
                            mLastLatitude, mLastLongitude);
                    setGeoLocationView(mLastLatitude, mLastLongitude, true);
                } else {
                    setGeoLocationView(mLatitude, mLongitude, false);
                }


//                if (Boolean.TRUE.equals(mViewModel.isConnected.getValue())) {
//                    mViewModel.distance.setValue(getString(R.string.fd_main_3));
//                    mLastLatitude = mLatitude;
//                    mLastLongitude = mLongitude;
//                    binding.tvTitle.setText(data.getAddress());
//                    setGeoLocationView(mLatitude, mLongitude, true);
//                } else {
//                    // 计算距离
//                    if (mLastLatitude > 0 && mLastLongitude > 0) {
//                        double distance = MapUtils.calculateDistance(mLatitude, mLongitude,
//                                mLastLatitude, mLastLongitude);
//                        setGeoLocationView(mLastLatitude, mLastLongitude, true);
//                    } else {
//                        setGeoLocationView(mLatitude, mLongitude, false);
//                    }
//                }
            }
        });
    }
    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mMapView.onDestroy();
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }


    private final OnClickEvent onClickEvent = new OnClickEvent() {
        @Override
        public void singleClick(View v) {
            if (v.getId() == R.id.iv_back) {
                if (getActivity() != null) {
                    getActivity().finish();
                }
            } else if (v.getId() == R.id.iv_get_location) {

            } else if (v.getId() == R.id.iv_guide) {

            } else if (v.getId() == R.id.iv_play_pause) {
                showTipsDialog();
            }
        }
    };

    private void showTipsDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_play_sound_tips, null);
        CommonDialog dialog = new CommonDialog(getActivity(),dialogView);
        dialog.setWidth(R.dimen.dp_316);
        dialog.setCancelable(true);
        dialog.setGravity(Gravity.CENTER);
        dialog.showDialog();

        AppCompatButton cancel = dialogView.findViewById(R.id.btn_cancel);
        cancel.setOnClickListener(v -> dialog.dismissDialog());

        AppCompatButton confirm = dialogView.findViewById(R.id.btn_confirm);
        confirm.setOnClickListener(v -> {
            dialog.dismissDialog();
        });


    }



    private void onLocationEmpty() {
        mLastLatitude = -1;
        mLastLongitude = -1;
//        binding.tvTime.setText("");
//        mViewModel.distance.setValue(getString(R.string.fd_main_8));
//        if (!binding.tvTitle.getText().toString().isEmpty()) return;
//        binding.tvTitle.setText(getString(R.string.fd_main_8));
    }

    private void setGeoLocationView(double latitude, double longitude, boolean isAddMarker) {
        LatLng latLng = new LatLng(latitude, longitude);
        mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20f));

        if (!isAddMarker) {
            return;
        }
        final MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.draggable(false);//设置Marker可拖动
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.ic_find_device_location)));
        mAMap.clear();
        mAMap.addMarker(markerOption);
        AMap.OnMarkerClickListener markerClickListener = marker -> {
            // 返回 true 则表示接口已响应事件，否则返回false
            onMapFind();
            return true;
        };
        mAMap.setOnMarkerClickListener(markerClickListener);
    }

    private void onMapFind() {
        if (mLastLatitude < 0 || mLastLongitude < 0) {
            ToastUtils.show("未获取到定位信息");
        } else {
//            SearchEarphoneNavDialogFragment dialog = new SearchEarphoneNavDialogFragment();
//            Bundle bundle = new Bundle();
//            bundle.putDouble("latitude", mLastLatitude);
//            bundle.putDouble("longitude", mLastLongitude);
//            bundle.putString("address", binding.tvTitle.getText().toString());
//            bundle.putInt("mapType", 1);
//            dialog.setArguments(bundle);
//            dialog.showDialog(SearchEarphoneActivity.this, dialog);
        }
    }

}
